/**
 * Copyright(C): CETC-32
 * @Title: CenterAuthShiroConfig
 * @Description: 自定义Realm
 * @author: youqing
 * @version: 1.0
 * @date: 2020/9/11 10:55
 * 更改描述：
 */

package com.cetc32.dh.common.shiro;

import com.cetc32.dh.dto.PermissionDTO;
import com.cetc32.dh.entity.BaseAdminPermission;
import com.cetc32.dh.entity.BaseAdminRole;
import com.cetc32.dh.entity.BaseAdminUser;
import com.cetc32.dh.mybatis.BaseAdminPermissionMapper;
import com.cetc32.dh.mybatis.BaseAdminRoleMapper;
import com.cetc32.dh.service.AdminRoleService;
import com.cetc32.dh.service.AdminUserService;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
/**
 * Token检查类
 * @Title: FormFilter
 * @version: 1.0
 * @date: 2020/9/11 10:55
 */
public class CustomRealm extends CasRealm {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AdminUserService userService;
    @Autowired
    private BaseAdminUser baseAdminUser;
    @Autowired
    private AdminRoleService roleService;
    @Autowired
    private BaseAdminPermissionMapper permissionMapper;
    @Autowired
    private BaseAdminRoleMapper roleMapper;
    //模拟数据库的数据
    Map<String,String> map=new HashMap();
    {
        map.put("jarWorker","123");
        super.setName("customRealm");
    }
    /**
     * 授权使用
     * @param principals
     * @return
     */
    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     * 修改信息：
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        BaseAdminUser  userName=(BaseAdminUser) principals.getPrimaryPrincipal();
        Set<String> roles=getRolesByUserName(userName.getSysUserName());
        Set<String> permissions=getPermissionsByUserName(userName.getSysUserName());
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        log.info("开始授权");
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }


    /**
     * 认证使用
     * @param
     * @return
     */
    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     * 修改信息：
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        //从主体传过来的认证信息中获取用户名
//        String userName=(String) token.getPrincipal();//获取用户名
//        String passWord=getPassword(userName);
//        if(passWord==null){
//            return null;
//        }
//        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo("",passWord,"customRealm");
//        return simpleAuthenticationInfo;
        //UsernamePasswordToken用于存放提交的登录信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        log.info("用户登录认证：验证当前Subject时获取到token为：" + ReflectionToStringBuilder
                .toString(token, ToStringStyle.MULTI_LINE_STYLE));
        String username = token.getUsername();
        // 调用数据层
        BaseAdminUser sysUser = userService.findByUserName(username);
        log.debug("用户登录认证！用户信息user：" + sysUser);
        if (sysUser == null) {
            // 用户不存在
            return null;
        }
        // 返回密码
        return new SimpleAuthenticationInfo(sysUser, sysUser.getSysUserPwd(), ByteSource.Util.bytes(username), getName());

    }

    /**
     * 数据库信息获取用户密码
     * @param userName
     * @return
     */
    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     * 修改信息：
     */
    private String getPassword(String userName) {
        if(null==userName){
            return  null;
        }
        BaseAdminUser adminUser = new BaseAdminUser();
        adminUser = userService.findByUserName(userName);
        String pwd = adminUser.getSysUserPwd();
        return pwd;
    }

    /**
     * 数据库获取用户角色
     * @param userName
     * @return
     */
    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     * 修改信息：
     */
    private Set<String> getRolesByUserName(String userName) {
//        Set<String> roles=new HashSet<String>();
//        roles.add("admin");
//        roles.add("tourist");
//        return  roles;

        Set<String> roles = new HashSet<String>();
        BaseAdminUser adminUser = new BaseAdminUser();
        adminUser = userService.findByUserName(userName);
        int rolid = adminUser.getRoleId();
        BaseAdminRole adminRole = new BaseAdminRole();
        adminRole = roleMapper.selectByPrimaryKey(rolid);
        String role = new String();
        role = adminRole.getRoleName();
        roles.add(role);
        return roles;

    }

    /**
     * 模拟数据库获取用户权限
     * @param userName
     * @return
     */
    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     * 修改信息：
     */
    private Set<String> getPermissionsByUserName(String userName) {
        /*Set<String> permissions=new HashSet<String>();
        permissions.add("user:update");
        permissions.add("user:query");
        return  permissions;*/
        Set<String> per = new HashSet<String>();
        BaseAdminUser adminUser = new BaseAdminUser();
        adminUser = userService.findByUserName(userName);
        int rolid = adminUser.getRoleId();
        BaseAdminRole role = new BaseAdminRole();
        role = roleService.findRoleById(rolid);

        if (null != role ) {
            String permissions = role.getPermissions();

            String[] ids = permissions.split(",");
            List<PermissionDTO> permissionList = new ArrayList <>();

            for (String id : ids) {
                // 角色对应的权限数据
                BaseAdminPermission perm = permissionMapper.selectByPrimaryKey(id);
                if (null != perm ) {
                    // 授权角色下所有权限
                    PermissionDTO permissionDTO = new PermissionDTO();
                    BeanUtils.copyProperties(perm,permissionDTO);
                    //获取子权限
                    List<PermissionDTO> childrens = permissionMapper.getPermissionListByPId(perm.getId());
                    permissionDTO.setChildrens(childrens);

                    permissionList.add(permissionDTO);
                }
            }

            for(PermissionDTO permissionDTO:permissionList){
                per.add(permissionDTO.getName());
            }


        }
        return  per;

    }
}
